<template>
	<view class="cart-container">
		<!-- 商品列表 -->
		<view class="cart-list" v-if="list.length > 0">
			<uni-swipe-action>
				<uni-swipe-action-item v-for="(item, index) in list" :key="index" :right-options="swipeOptions"
					@click="handleSwipeClick($event, index)">
					<view class="cart-item">
						<!-- 选择框 -->
						<view class="item-select" @click="toggleSelect(index)">
							<view class="checkbox" :class="{ 'checked': item.selected }">
								<text v-if="item.selected" class="check-icon">✓</text>
							</view>
						</view>

						<!-- 商品信息 -->
						<view class="item-info" @click="showAttributeModal(index)">
							<image class="item-image" :src="item.sku.imageUrl" mode="aspectFill"></image>
							<view class="item-details">
								<text class="item-title">{{ item.spu.name }}</text>
								<view class="item-attributes" @click.stop="showAttributeModal(index)">
									<text class="attribute-text">{{ formatSpec(item.sku.spec) }}</text>
								</view>
								<view class="item-price">
									<text class="price">¥{{ item.sku.price }}</text>
									<view class="quantity-control">
										<text class="quantity-btn" @click.stop="decreaseQuantity(index)">-</text>
										<text class="quantity-text">{{ item.quantity || 1 }}</text>
										<text class="quantity-btn" @click.stop="increaseQuantity(index)">+</text>
									</view>
								</view>
							</view>
						</view>
					</view>
				</uni-swipe-action-item>
			</uni-swipe-action>
		</view>

		<!-- 空购物车提示 -->
		<view class="empty-cart" v-else>
			<image class="empty-image" src="/static/cart/购物车空.png" mode="aspectFit"></image>
			<text class="empty-text">购物车空空如也~</text>
		</view>

		<!-- 推荐专区 -->
		<view class="recommend-section">
			<text class="recommend-title">为你推荐</text>
			<view class="recommend-list">
				<view class="recommend-item" v-for="(item, index) in recommendGoods" :key="index"
					@click="viewProduct(item)">
					<image class="recommend-img" :src="item.image" mode="aspectFill"></image>
					<text class="recommend-name">{{ item.name }}</text>
					<text class="recommend-price">¥{{ item.price }}</text>
				</view>
			</view>
		</view>

		<!-- 底部结算栏 -->
		<view class="cart-footer" v-if="list.length > 0">
			<view class="select-all" @click="toggleSelectAll">
				<view class="checkbox" :class="{ 'checked': allSelected }">
					<text v-if="allSelected" class="check-icon">✓</text>
				</view>
				<text class="select-all-text">全选</text>
			</view>
			<view class="total-info">
				<text class="total-text">合计: ¥{{ totalPrice.toFixed(2) }}</text>
			</view>
			<view class="checkout-btn" :class="{ 'disabled': selectedCount === 0 }" @click="checkout">
				<text class="checkout-text">去结算({{ selectedCount }})</text>
			</view>
		</view>
	</view>
</template>

<script>
	import { get } from "@/utils/request";
	import { jwtDecode } from 'jwt-decode';

	export default {
		data() {
			return {
				pageNum: 1,
				pageSize: 10,
				membersId: null,
				list: [],
				swipeOptions: [{
					text: '收藏',
					style: {
						backgroundColor: '#ff9500'
					}
				}, {
					text: '删除',
					style: {
						backgroundColor: '#ff4444'
					}
				}],
				recommendGoods: [{
						id: 1,
						image: '/static/swy/p0.jpg',
						name: '推荐商品1',
						price: 99.00
					},
					{
						id: 2,
						image: '/static/swy/p0.jpg',
						name: '推荐商品2',
						price: 129.00
					},
					{
						id: 3,
						image: '/static/swy/p0.jpg',
						name: '推荐商品3',
						price: 79.00
					},
					{
						id: 4,
						image: '/static/swy/p0.jpg',
						name: '推荐商品4',
						price: 199.00
					}
				]
			};
		},
		computed: {
			allSelected() {
				return this.list.length > 0 && this.list.every(item => item.selected);
			},
			selectedCount() {
				return this.list.filter(item => item.selected).length;
			},
			totalPrice() {
				return this.list
					.filter(item => item.selected)
					.reduce((total, item) => total + (item.sku.price * (item.quantity || 1)), 0);
			}
		},
		onLoad() {
			this.getData();
		},
		methods: {
			getData() {
				const token = uni.getStorageSync('token');
				let userId = null;

				if (token) {
					try {
						const decoded = jwtDecode(token);
						userId = decoded.user_id;
						this.membersId = userId;
					} catch (e) {
						console.error('Token 解析失败', e);
					}
				}

				if (!userId) {
					uni.showToast({
						title: '用户信息无效，请重新登录',
						icon: 'none'
					});
					return;
				}

				get("/transaction/item/list", {
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					membersId: userId
				}).then((res) => {
					if (res.code === 200 && Array.isArray(res.rows)) {
						this.list = res.rows.map(item => ({
							...item,
							selected: false,
							quantity: 1
						}));
					} else {
						uni.showToast({
							title: "数据加载失败",
							icon: "none"
						});
					}
				});
			},

			formatSpec(specJson) {
				try {
					const obj = JSON.parse(specJson);
					return Object.values(obj).join(" / ");
				} catch {
					return specJson;
				}
			},
			
			toggleSelect(index) {
				this.list[index].selected = !this.list[index].selected;
			},
			
			toggleSelectAll() {
				const newState = !this.allSelected;
				this.list.forEach(item => {
					item.selected = newState;
				});
			},
			
			increaseQuantity(index) {
				this.list[index].quantity++;
			},
			
			decreaseQuantity(index) {
				if (this.list[index].quantity > 1) {
					this.list[index].quantity--;
				}
			},
			
			handleSwipeClick(e, index) {
				if (e.index === 0) {
					this.collectItem(index);
				} else if (e.index === 1) {
					this.deleteItem(index);
				}
			},
			
			collectItem(index) {
				uni.showToast({
					title: '已收藏',
					icon: 'success'
				});
			},
			
			deleteItem(index) {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这个商品吗？',
					success: (res) => {
						if (res.confirm) {
							this.list.splice(index, 1);
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
						}
					}
				});
			},
			
			checkout() {
				if (this.selectedCount === 0) {
					uni.showToast({
						title: '请选择商品',
						icon: 'none'
					});
					return;
				}

				const token = uni.getStorageSync('token');
				let userId = null;

				if (token) {
					try {
						const decoded = jwtDecode(token);
						userId = decoded.user_id;
					} catch (e) {
						console.error('Token 解析失败', e);
					}
				}

				const selectedItems = this.list.filter(item => item.selected).map(item => ({
					spu: item.spu,
					sku: item.sku,
					quantity: item.quantity || 1,
					selectedAttributes: JSON.parse(item.sku.spec)
				}));
				
				uni.navigateTo({
					url: `/pages/FillOrderDetail/FillOrderDetail?userId=${userId}`,
					success: () => {
						getApp().globalData = getApp().globalData || {};
						getApp().globalData.selectedItems = selectedItems;
					}
				});
			},
			
			viewProduct(item) {
				uni.navigateTo({
					url: '/pages/product-detail/index'
				});
			}
		}
	}
</script>

<style scoped>
	.cart-container {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 120rpx;
	}

	.cart-list {
		background-color: #fff;
	}

	.cart-item {
		display: flex;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.item-select {
		margin-right: 20rpx;
	}

	.checkbox {
		width: 40rpx;
		height: 40rpx;
		border: 2rpx solid #ddd;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.checkbox.checked {
		background-color: #ff4444;
		border-color: #ff4444;
	}

	.check-icon {
		color: #fff;
		font-size: 24rpx;
		font-weight: bold;
	}

	.item-info {
		flex: 1;
		display: flex;
	}

	.item-image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 8rpx;
		margin-right: 20rpx;
	}

	.item-details {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.item-title {
		font-size: 28rpx;
		color: #333;
		line-height: 1.4;
		margin-bottom: 10rpx;
	}

	.item-attributes {
		background-color: #f8f8f8;
		padding: 10rpx 20rpx;
		border-radius: 6rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 10rpx;
	}

	.attribute-text {
		font-size: 24rpx;
		color: #666;
	}

	.item-price {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.price {
		font-size: 32rpx;
		color: #ff4444;
		font-weight: bold;
	}

	.quantity-control {
		display: flex;
		align-items: center;
		border: 1rpx solid #ddd;
		border-radius: 6rpx;
	}

	.quantity-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f8f8f8;
		font-size: 28rpx;
		color: #333;
	}

	.quantity-text {
		width: 80rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		color: #333;
		background-color: #fff;
	}

	.empty-cart {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 200rpx 0;
	}

	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999;
	}

	.cart-footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		border-top: 1rpx solid #eee;
		z-index: 100;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.select-all {
		display: flex;
		align-items: center;
		margin-right: 30rpx;
	}

	.select-all-text {
		font-size: 28rpx;
		color: #333;
		margin-left: 10rpx;
	}

	.total-info {
		flex: 1;
	}

	.total-text {
		font-size: 28rpx;
		color: #333;
	}

	.checkout-btn {
		background-color: #ff4444;
		padding: 20rpx 40rpx;
		border-radius: 8rpx;
	}

	.checkout-btn.disabled {
		background-color: #ccc;
	}

	.checkout-text {
		font-size: 28rpx;
		color: #fff;
	}

	.recommend-section {
		margin-top: 30rpx;
		background-color: #fff;
		padding: 30rpx;
	}

	.recommend-title {
		display: block;
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
		margin-bottom: 30rpx;
	}

	.recommend-list {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 20rpx;
	}

	.recommend-item {
		background-color: #fff;
		border-radius: 12rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.recommend-img {
		width: 100%;
		height: 300rpx;
	}

	.recommend-name {
		display: block;
		font-size: 26rpx;
		color: #333;
		padding: 15rpx;
		line-height: 1.3;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}

	.recommend-price {
		display: block;
		font-size: 28rpx;
		color: #ff2a3a;
		font-weight: bold;
		padding: 0 15rpx 15rpx;
	}
</style>